from collections import OrderedDict

from django.shortcuts import render

# Create your views here.

# 1.商城的首页会被频繁访问的到，造成 数据库的查询频率很大
# 2.  如果我们把数据给前端（或者自己渲染） 会影响效率


# 优化
#1. 把首页请求的数据 缓存起来 这个可以的

# 2. 静态化  --其实就是我们将渲染好的页面 以
#           html的形式写入到文件中，让用户直接访问我们渲染好的页面

#   2.1     静态化的前期准备工作

from django.views import View

from contents.models import ContentCategory
from goods.models import GoodsChannel


# 首页数据经常变化，所以采用 定时任务

# 列表页面 因为有些数据是不经常变化，只有在有些数据被触发的时候才会发生变化 Celery的异步任务


class HomeView(View):

    def get(self,request):

            #1.获取数据
            # 使用有序字典保存类别的顺序
            # categories = {
            #     1: { # 组1
            #         'channels': [{'id':, 'name':, 'url':},{}, {}...],
            #         'sub_cats': [{'id':, 'name':, 'sub_cats':[{},{}]}, {}, {}, ..]
            #     },
            #     2: { # 组2
            #
            #     }
            # }
            # 初始化存储容器
            categories = OrderedDict()
            # 获取一级分类
            channels = GoodsChannel.objects.order_by('group_id', 'sequence')

            # 对一级分类进行遍历
            for channel in channels:
                # 获取group_id
                group_id = channel.group_id
                # 判断group_id 是否在存储容器,如果不在就初始化
                if group_id not in categories:
                    categories[group_id] = {
                        'channels': [],
                        'sub_cats': []
                    }

                one = channel.category
                # 为channels填充数据
                categories[group_id]['channels'].append({
                    'id': one.id,
                    'name': one.name,
                    'url': channel.url
                })
                # 为sub_cats填充数据
                for two in one.goodscategory_set.all():
                    # 初始化 容器
                    two.sub_cats = []
                    # 遍历获取
                    for three in two.goodscategory_set.all():
                        two.sub_cats.append(three)

                    # 组织数据
                    categories[group_id]['sub_cats'].append(two)

            # 广告和首页数据
            contents = {}
            content_categories = ContentCategory.objects.all()
            # content_categories = [{'name':xx , 'key': 'index_new'}, {}, {}]

            # {
            #    'index_new': [] ,
            #    'index_lbt': []
            # }
            for cat in content_categories:
                contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')


            #2. 渲染
            context = {
                'categories': categories,
                'contents': contents
            }
            return render(request, 'index.html', context)


from rest_framework.views import APIView
from rest_framework.generics import ListAPIView
from .serialziers import SKUSerializer
from .models import SKU
class HotSKUListAPIView(ListAPIView):

    pagination_class = None

    """
    GET     categories/(?P<category_id>\d+)/hotskus/
    1.
    """

    serializer_class = SKUSerializer

    # queryset = SKU.objects.filter(category=115).order_by('-sales')[:2]

    def get_queryset(self):

        category_id = self.kwargs.get('category_id')

        return SKU.objects.filter(category=category_id).order_by('-sales')[:2]



from rest_framework.generics import GenericAPIView
class SKUListAPIView(ListAPIView):

    """
    GET     categories/(?P<category_id>\d+)/skus/
    1.
    """

    serializer_class = SKUSerializer

    # queryset = SKU.objects.filter(category=115).order_by('-sales')[:2]

    def get_queryset(self):

        category_id = self.kwargs.get('category_id')

        return SKU.objects.filter(category=category_id)


    #排序
    from rest_framework.filters import OrderingFilter
    filter_backends = [OrderingFilter]

    ordering_fields = ['create_time','price','sales']

    #分页
    # from rest_framework.pagination import LimitOffsetPagination
    # pagination_class = LimitOffsetPagination

    # from rest_framework.pagination import PageNumberPagination



from .serialziers import SKUIndexSerializer
from drf_haystack.viewsets import HaystackViewSet

class SKUSearchViewSet(HaystackViewSet):
    """
    SKU搜索
    """
    index_models = [SKU]

    serializer_class = SKUIndexSerializer

